import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter/material.dart';
import 'package:chat_shop/common/const/cosnt.dart';
import 'package:chat_shop/common/network/network.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:zevent_bus/zevent_bus.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  List<dynamic> data = [];
  List<dynamic> bannerList = [];
  @override
  void initState() {
    super.initState();
    _getData();
  }

  void _getData() {
    Networktool.request("v2/list", method: HTTPMETHOD.GET, success: (sender) {
      print("$sender");
      setState(() {
        data.addAll(sender);
      });
    });

    Networktool.request("v2/list", method: HTTPMETHOD.GET, success: (sender) {
      print("$sender");
      if (sender is List) {
        setState(() {
          bannerList.addAll(sender.skip(sender.length ~/ 3).take(sender.length ~/ 3).toList());
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            pinned: true,
            centerTitle: true,
            backgroundColor: AppColor.mainColor,
            leading: const SizedBox(),
            title: Text(
              "首页",
              style: TextStyle(fontSize: 16, color: Colors.white),
            ),
          ),
          SliverToBoxAdapter(
            child: SizedBox(
              height: 180,
              child: Swiper(
                itemBuilder: (BuildContext context, int index) {
                  return Stack(
                    children: <Widget>[
                      SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: AspectRatio(
                          aspectRatio: 75 / 54,
                          child: CachedNetworkImage(
                            imageUrl: bannerList[index]['download_url'],
                            fit: BoxFit.cover,
                            fadeInDuration: Duration.zero,
                            placeholder: (BuildContext context, String url) {
                              return Placeholder();
                            },
                          ),
                        ),
                      ),
                    ],
                  );
                },
                itemCount: bannerList.length,
                autoplay: true,
                pagination: const SwiperPagination(),
              ),
            ),
          ),
          SliverPadding(
            padding: const EdgeInsets.all(12),
            sliver: SliverWaterfallFlow(
              gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                crossAxisCount: data.length == 0 ? 1 : 2,
                crossAxisSpacing: 8,
                mainAxisSpacing: 8,
              ),
              delegate: SliverChildBuilderDelegate(
                (BuildContext c, int index) {
                  if (data.isEmpty) {
                    return Column(
                      children: [
                        CupertinoActivityIndicator(
                          color: Colors.grey,
                        ),
                        Text(
                          "数据加载中...",
                          style: TextStyle(fontSize: 17, color: Colors.grey),
                        )
                      ],
                    );
                  }
                  return _Card(
                    model: data[index],
                    height: index % 2 == 0 ? 100 : 200,
                  );
                },
                childCount: data.length == 0 ? 1 : data.length,
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _Card extends StatelessWidget {
  final Map<String, dynamic> model;
  final double height;
  const _Card({Key? key, required this.model, required this.height}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: height,
          child: PhysicalModel(
            borderRadius: BorderRadius.circular(12),
            clipBehavior: Clip.antiAlias,
            color: Colors.transparent,
            child: CachedNetworkImage(
              imageUrl: model["download_url"],
              fit: BoxFit.cover,
            ),
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              model["author"],
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, height: 28 / 18),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 4, bottom: 4),
              child: Row(
                children: [
                  Icon(
                    Icons.share,
                    color: Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(width: 10),
                  Icon(
                    Icons.message,
                    color: Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(fontSize: 11, color: Colors.grey),
                  ),
                  const SizedBox(width: 10),
                  Icon(
                    int.parse(model["id"]) % 2 == 0 ? Icons.favorite : Icons.favorite_border_sharp,
                    color: int.parse(model["id"]) % 2 == 0 ? Colors.red : Colors.grey,
                    size: 10,
                  ),
                  Text(
                    "${model["id"]}",
                    style: TextStyle(fontSize: 11, color: Colors.grey),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                Text(
                  "\$${model["height"] ~/ 100}",
                  style: TextStyle(fontWeight: FontWeight.bold, color: Colors.redAccent, fontSize: 18, height: 28 / 18),
                ),
                Spacer(),
                Icon(
                  Icons.add_shopping_cart,
                  size: 16,
                  color: Colors.redAccent,
                )
              ],
            )
          ],
        )
      ],
    );
  }
}
